﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;

using WinFormsUI.Docking;

using ChaSQLite.SQLiteManage;

namespace ChaSQLite.SubForm
{
    public partial class DynamicQueryViewer : DockContent, IMessageFilter
    {
        private string title = "QueryEditor";
        private SplitContainer[] subSplitter = null;
        private ListView[] lstView = null;

        public string Title
        {
            get { return title; }
            set { title = value; }
        }

        public DynamicQueryViewer()
        {
            InitializeComponent();
        }

        private void QueryViewer_Load(object sender, EventArgs e)
        {
            this.mainSplitter.Panel2Collapsed = true;
            this.Text = title;
            this.TabText = title;            
        }

        private bool doQuery(string query, int nQuery)
        {
            query = query.Trim();
            char [] value = new char[] { ' ', '\t' };
            int nIndex = query.IndexOfAny(value);
            string cmd = null;

            if (nIndex > 0)
            {
                cmd = query.Substring(0, nIndex);
                if (cmd.ToUpper().Equals("SELECT") == false)
                    cmd = null;
            }

            if (cmd == null)
            {
                SQLManager.getInstance.GetBase.ExecuteNonQuery(query);
                return true;
            }

            //try 
            {
                DataTable table = SQLManager.getInstance.GetBase.ExecuteQuery(query);
                
                if (table.Columns.Count == 0)
                    return false;

                int nColumns = table.Columns.Count;
                string[] colName = new string[nColumns];
                int nCount = 0;

                //lstResult.Clear();
                //lstResult.Columns.Clear();                
                lstView[nQuery].Columns.Clear();

                foreach (DataColumn col in table.Columns)
                {
                    colName[nCount++] = col.ToString();
                    //lstResult.Columns.Add(col.ToString());
                    lstView[nQuery].Columns.Add(col.ToString());
                }

                int nFirst = 0;
                //ListViewItem item;
                bool r = false;
                foreach (DataRow row in table.Rows)
                {
                    nFirst = 0;
                    foreach (DataColumn column in table.Columns)
                    {
                        colName[nFirst++] = row[column].ToString();
                    }

                    ListViewItem newItem = new ListViewItem( colName, 0 ); //info.Message }, imageindex);
                    if (r == true)
                        newItem.BackColor = Color.FromName("WhiteSmoke");
                    
                    //lstResult.Items.Add(newItem);
                    lstView[nQuery].Items.Add(newItem);
                    r = r == false ? true : false;
                }

                this.mainSplitter.Panel2Collapsed = false;
                lstView[nQuery].AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                lstView[nQuery].AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            }
            //catch(Exception e)
            {
            //    MessageBox.Show( e.Message, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error );
            }

            return true;
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {
            mainSplitter.Panel2.Controls.Clear();
            lstView = null;
            subSplitter = null;
 
            List<string> querys = getQueryStrings(txtQueryString.Text);
            if( querys.Count > 1 )
                subSplitter = new SplitContainer[querys.Count-1];
            lstView = new ListView[querys.Count];

            if (querys.Count == 1)
            {
                lstView[0] = new ListView();
                lstView[0].Font = new System.Drawing.Font("맑은 고딕", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));
                mainSplitter.Panel2.Controls.Add(lstView[0]);
                lstView[0].Dock = DockStyle.Fill;
                lstView[0].View = System.Windows.Forms.View.Details;
                lstView[0].FullRowSelect = true;
                lstView[0].GridLines = true;
                lstView[0].Location = new System.Drawing.Point(0, 0);
                lstView[0].UseCompatibleStateImageBehavior = false;
                lstView[0].View = System.Windows.Forms.View.Details;                
            }
            else
            {
                int nQuery = 0;
                foreach (string query in querys)
                {
                    lstView[nQuery] = new ListView();
                    lstView[nQuery].Font = new System.Drawing.Font("맑은 고딕", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));

                    lstView[nQuery].FullRowSelect = true;
                    lstView[nQuery].GridLines = true;
                    lstView[nQuery].Location = new System.Drawing.Point(0, 0);
                    lstView[nQuery].UseCompatibleStateImageBehavior = false;
                    lstView[nQuery].View = System.Windows.Forms.View.Details;                    

                    if (nQuery == 0)
                    {                        
                        subSplitter[nQuery] = new SplitContainer();
                        mainSplitter.Panel2.Controls.Add(subSplitter[nQuery]);
                        subSplitter[nQuery].Dock = DockStyle.Fill;
                        subSplitter[nQuery].Panel1.Controls.Add(lstView[nQuery]);                        
                        lstView[nQuery].Dock = DockStyle.Fill;
                        subSplitter[nQuery].Orientation = Orientation.Horizontal;

                        mainSplitter.SplitterDistance = 60;
                    }
                    else if (nQuery + 1 != querys.Count)
                    {
                        subSplitter[nQuery] = new SplitContainer();
                        subSplitter[nQuery-1].Panel2.Controls.Add(subSplitter[nQuery]);                        
                        subSplitter[nQuery].Dock = DockStyle.Fill;
                        subSplitter[nQuery].Panel1.Controls.Add(lstView[nQuery]);
                        lstView[nQuery].Dock = DockStyle.Fill;
                        subSplitter[nQuery].Orientation = Orientation.Horizontal;
                        subSplitter[nQuery].SplitterDistance = 60;
                    }
                    else
                    {
                        subSplitter[nQuery-1].Panel2.Controls.Add(lstView[nQuery]);
                        lstView[nQuery].Dock = DockStyle.Fill;
                    }
                    
                    nQuery++;
                }            
            }
            
            for ( int i = 0; i < querys.Count; i++ )
            {
                doQuery(querys[i], i);
            }

            this.mainSplitter.Panel2Collapsed = false;
        }

        private List<string> getQueryStrings(string query)
        {
            List<string> arr = new List<string>();
            int nCount = query.Length;
            string queryText = "";

            for (int i = 0; i < nCount; i++)
            {
                if (query[i] == ';')
                {
                    arr.Add(queryText);
                    queryText = "";
                }
                else if (query[i] == '\n' || query[i] == '\r')
                    continue;
                else
                {
                    queryText += query[i];
                }
            }
            if ( queryText.Length > 10 )
                arr.Add(queryText);
            
            return arr;
        }

        private void btnFont_Click(object sender, EventArgs e)
        {
            fontDialog = new FontDialog();
            if (fontDialog.ShowDialog() == DialogResult.Cancel)
                return;

            string name = fontDialog.Font.Name;

            txtQueryString.Font = fontDialog.Font;
        }

        public bool PreFilterMessage(ref Message msg)
        {
            if (this.IsActivated == false)
                return false;

            switch (msg.Msg)
            {
                case ( 256 )://WM_KEYDOWN):
                    // 여기에서 원하는 작업을 하고...
                    //MessageBox.Show("WM_LBUTTONDOWN is : " + msg.LParam.ToInt32().ToString());
                    if (msg.LParam.ToInt32() == 4128769) // F5
                    {

                        //MessageBox.Show("WM_LBUTTONDOWN is : " + msg.Msg.ToString());
                        btnExecute_Click(null, null);
                        return true;
                    }
                    if (msg.LParam.ToInt32() == 22020097 )  // 화살표 아래..
                    {
                        //MessageBox.Show("-------");
                        return true;
                    }

                    break;
            }
            return false;

        }        
    }
}
